package com.transaction.seataorder.server.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.transaction.seataorder.api.StockControl;
import com.transaction.seataorder.mapper.OrderMapper;
import com.transaction.seataorder.model.Order;
import com.transaction.seataorder.server.IOrderServer;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;


/**
 * @author ausu
 * @version 1.0
 * @description: TODO
 * @date 2022/12/22 20:05
 */
@Service
public class OrderServerImpl extends ServiceImpl<OrderMapper,Order> implements IOrderServer {

    @Autowired(required = false)
    private OrderMapper orderMapper;

//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private StockControl stockControl;

    @Override
    //todo 可以控制远端事务，但不可以控制本地事务
    @GlobalTransactional
    //TODO 加@Transactional注解才可以控制本地事务
    @Transactional
    public String create(Order order) {
        // 创建订单
        int num = orderMapper.insert(order);
        System.out.println("创建订单:" + num);
        System.out.println("===============");

        // 利用RestTemplate，调用库存微服务中的方法
        Integer productId = order.getProductId();
//        String forObject = restTemplate.getForObject("http://localhost:8002/stock?productId={1}", String.class, productId);
//        System.out.println("The Stock result:"+ forObject);

        // 利用OpenFeign远程调用
        String s = stockControl.deductStock(productId);
        System.out.println("库存微服务的返回值:::"+ s);

        // 出现运行时异常（java.lang.ArithmeticException: / by zero）， 未进行回滚。
        int i=9;
        int j = i/0;

        return "ok";
    }
}
